﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Threading;
using System.IO;
using System.Diagnostics;

namespace Eagle.WindowServiceUI
{
    public partial class ServerMonitor : Form
    {
        private static System.Threading.Timer timer = null;
        private static string errorFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log/errorlog");
        private static string errorFilePath = Path.Combine(errorFolder, "error.txt");
        public ServerMonitor()
        {
            InitializeComponent();
        }

        #region 事件
        protected override void OnLoad(EventArgs e)
        {
            if (!Directory.Exists(errorFolder))
                Directory.CreateDirectory(errorFolder);
            timer = new System.Threading.Timer(new TimerCallback(delegate { CheckError(); }), null, 1000 * 30, 1000 * 30);
            this.ChangeButtonStatus(false, false);
            if (!ServiceIsExisted(ServiceConfig.Instance.ServiceName))
            {
                this.ChangeButtonStatus(true, false);
                this.ServiceStateText.Text = "未找到服务(" + ServiceConfig.Instance.ServiceName + ")";
            }
            else
            {
                  ServiceController controller = new ServiceController(ServiceConfig.Instance.ServiceName);
                switch (controller.Status)
                {
                    case ServiceControllerStatus.Running:
                        this.ChangeButtonStatus(false, true);
                        this.ServiceStateText.Text = "服务运行中...";
                        break;
                    case ServiceControllerStatus.Stopped:
                        this.ChangeButtonStatus(true, false);
                        this.ServiceStateText.Text = "服务已经停止...";
                        break;
                    //case ServiceControllerStatus.ContinuePending:
                    //      this.ChangeButtonStatus(true, true, true, false);
                    //      break;
                    default:
                        this.ServiceStateText.Text = "未知状态:" + controller.Status.ToString();
                        break;
                }
            }
            base.OnLoad(e);
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (timer != null)
                timer.Dispose();
            base.OnClosing(e);
        }

        private void StartServiceButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (!ServiceIsExisted(ServiceConfig.Instance.ServiceName))
                {
                    this.ChangeButtonStatus(true, false);
                    this.ServiceStateText.Text = "未找到服务(" + ServiceConfig.Instance.ServiceName + ")";
                    MessageBox.Show("未找到服务(" + ServiceConfig.Instance.ServiceName + ")");
                    return;
                }
                ServiceController controller = new ServiceController(ServiceConfig.Instance.ServiceName);
                if (controller.Status == ServiceControllerStatus.Running)
                {
                    this.ServiceStateText.Text = "服务运行中...";
                }
                controller.Start();
                this.ServiceStateText.Text = "服务运行中...";
                this.ChangeButtonStatus(false, true);
            }
            catch (Exception ex)
            {
                RecordLog(ex.ToString());
                MessageBox.Show("异常错误：" + ex.Message);
            }
        }

        private void StopServiceButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (!ServiceIsExisted(ServiceConfig.Instance.ServiceName))
                {
                    this.ChangeButtonStatus(true, false);
                    this.ServiceStateText.Text = "未找到服务(" + ServiceConfig.Instance.ServiceName + ")";
                    MessageBox.Show("未找到服务(" + ServiceConfig.Instance.ServiceName + ")");
                    return;
                }
                ServiceController controller = new ServiceController(ServiceConfig.Instance.ServiceName);
                if (controller.Status == ServiceControllerStatus.Stopped)
                {
                    this.ServiceStateText.Text = "服务已经停止...";
                }
                if (controller.CanStop)
                    controller.Stop();
                this.ServiceStateText.Text = "服务已经停止...";
                this.ChangeButtonStatus(true, false);
            }
            catch (Exception ex)
            {
                RecordLog(ex.ToString());
                MessageBox.Show("异常错误：" + ex.Message);
            }
        }

        #endregion

        #region 改变按钮状态
        private void ChangeButtonStatus(bool start, bool stop)
        {
            this.StartServiceButton.Enabled = start;
            this.StopServiceButton.Enabled = stop;
        }
        private bool ServiceIsExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName == serviceName)
                {
                    return true;
                }
            }
            return false;
        }
        private void CheckError()
        {
              try
              {
                  if (File.Exists(errorFilePath))
                  {
                      FileInfo fileInfo = new FileInfo(errorFilePath);
                      if (DateTime.Now.Subtract(fileInfo.LastWriteTime).Days == 0)
                      {
                          this.ProgressLabel.BeginInvoke(new EventHandler(UpdateProgress), "今天有错误发生，点击打开错误文件夹");
                      }
                  }
                  else
                  { this.ProgressLabel.BeginInvoke(new EventHandler(UpdateProgress), "今天运行良好，无错误"); }
                      ServiceController controller = new ServiceController(ServiceConfig.Instance.ServiceName);
                      if (controller != null)
                      {
                          if (controller.Status == ServiceControllerStatus.Running)
                          {
                              this.ServiceStateText.BeginInvoke(new EventHandler(UpdateServiceStateText), "服务运行中...");
                          }
                          if (controller.Status == ServiceControllerStatus.Stopped)
                          {
                              this.ServiceStateText.BeginInvoke(new EventHandler(UpdateServiceStateText), "服务已经停止...");
                          }
                      }
              }
              catch(Exception ex)
              {
                  RecordLog(ex.ToString());
              }
        }
        private void UpdateProgress(object sender, EventArgs e)
        {
            this.ProgressLabel.Text = sender.ToString();
        }
        private void UpdateServiceStateText(object sender, EventArgs e)
        {
            this.ServiceStateText.Text = sender.ToString();
        }
        #endregion

        private void ProgressLabel_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(errorFolder))
            { System.Diagnostics.Process.Start(errorFolder); }
        }

        private void OpenHistoryDirectory_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(errorFolder))
            { System.Diagnostics.Process.Start(errorFolder); }
            else
            {
                MessageBox.Show("没有找到历史错误文件夹");
            }
        }

        private void RegisterServiceButton_Click(object sender, EventArgs e)
        {
            try
            {
                string installutilPath = @"C:\Windows\Microsoft.NET\Framework\v2.0.50727\installutil";
                Process p = new Process();
                p.StartInfo.FileName = "C:\\WINDOWS\\system32\\cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                p.Start();
                string strOutput = null;
                p.StandardInput.WriteLine(installutilPath + " " + ServiceConfig.Instance.PhysicalServicePath);
                p.StandardInput.WriteLine("exit");
                strOutput = p.StandardOutput.ReadToEnd();
                p.WaitForExit();
                MessageBox.Show("注册成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误：" + ex.Message);
            }
        }

        private void UnregisterServiceButton_Click(object sender, EventArgs e)
        {
            try
            {
                string installutilPath = @"C:\Windows\Microsoft.NET\Framework\v2.0.50727\installutil";
                Process p = new Process();
                p.StartInfo.FileName = "C:\\WINDOWS\\system32\\cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                p.Start();
                string strOutput = null;
                p.StandardInput.WriteLine(installutilPath + " /u " + ServiceConfig.Instance.PhysicalServicePath);
                p.StandardInput.WriteLine("exit");
                strOutput = p.StandardOutput.ReadToEnd();
                p.WaitForExit();
                MessageBox.Show("删除服务成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误：" + ex.Message);
            }
        }

        private void RecordLog(string value)
        {
            using (StreamWriter sw = new StreamWriter(errorFilePath, true, Encoding.GetEncoding("gb2312")))
            {
                sw.Write(value + Environment.NewLine);
            }
        }
    }
}
